package com.sc.es.service.house;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.sc.es.service.IQiNiuService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;

/**
 * @author sc
 * Created on  2018/2/7
 */
@Service
public class QiNiuService implements IQiNiuService,InitializingBean {
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private BucketManager bucketManager;
    @Autowired
    private Auth auth;

    @Value("${qiniu.Bucket}")
    private String bucket;
    @Value("${qiniu.RetryTime}")
    private int retryTime;

    StringMap putPolicy = new StringMap();


    @Override
    public Response uploadFile(File file) throws QiniuException {
        Response response = uploadManager.put(file, null, getUploadToken());
        while(response.needRetry()&&retryTime>0){
            response=uploadManager.put(file, null, getUploadToken());
            retryTime--;
        }
        return response;
    }

    @Override
    public Response uploadFile(InputStream inputStream) throws QiniuException {
        Response response = uploadManager.put(inputStream, null, getUploadToken(),null,null);
        while(response.needRetry()&&retryTime>0){
            response=uploadManager.put(inputStream, null, getUploadToken(),null,null);
            retryTime--;
        }
        return response;
    }

    @Override
    public Response deleteFile(String key) throws QiniuException {
        Response response = bucketManager.delete(bucket, key);
        while(response.needRetry()&&retryTime>0){
            response = bucketManager.delete(bucket, key);
            retryTime--;
        }
        return response;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        putPolicy.put("returnBody",
                "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width)" +
                        ",\"height\":$(imageInfo.height)}");
    }

    /***
     * 上传凭证
     * @return
     */
    private String getUploadToken(){
        return auth.uploadToken(bucket,null,3600,putPolicy);
    }
}
